package com.easylinkin.linkappapi.quality.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.utils.excel.ExcelReadUtil;
import com.easylinkin.linkappapi.concretestrength.dto.ConcreteStrengthPositionDTO;
import com.easylinkin.linkappapi.concretestrength.entity.ConcreteStrengthInfo;
import com.easylinkin.linkappapi.concretestrength.mapper.ConcreteStrengthInfoMapper;
import com.easylinkin.linkappapi.lobar.dto.GroupDTO;
import com.easylinkin.linkappapi.lobar.dto.LaborCompanyProjectDTO;
import com.easylinkin.linkappapi.lobar.mapper.GroupMapper;
import com.easylinkin.linkappapi.lobar.mapper.LaborCompanyProjectMapper;
import com.easylinkin.linkappapi.quality.dto.ActualMeasurePositionDTO;
import com.easylinkin.linkappapi.quality.dto.QualityPositionDTO;
import com.easylinkin.linkappapi.quality.entity.ActualMeasureInfo;
import com.easylinkin.linkappapi.quality.entity.QualityAppraisingExcellent;
import com.easylinkin.linkappapi.quality.entity.QualityDrawing;
import com.easylinkin.linkappapi.quality.entity.QualityInspection;
import com.easylinkin.linkappapi.quality.entity.QualityPosition;
import com.easylinkin.linkappapi.quality.entity.QualityQuestionInfo;
import com.easylinkin.linkappapi.quality.entity.vo.QualityPositionVo;
import com.easylinkin.linkappapi.quality.mapper.ActualMeasureInfoMapper;
import com.easylinkin.linkappapi.quality.mapper.QualityAppraisingExcellentMapper;
import com.easylinkin.linkappapi.quality.mapper.QualityDrawingMapper;
import com.easylinkin.linkappapi.quality.mapper.QualityInspectionMapper;
import com.easylinkin.linkappapi.quality.mapper.QualityPositionMapper;
import com.easylinkin.linkappapi.quality.mapper.QualityQuestionInfoMapper;
import com.easylinkin.linkappapi.quality.service.QualityPositionService;
import com.easylinkin.linkappapi.safe.dao.HiddenDangerMapper;
import com.easylinkin.linkappapi.safe.entity.HiddenDanger;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.security.mapper.LinkappUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 闸机表 服务实现类
 * </p>
 *
 * @author TongJie
 * @since 2022-04-13
 */
@Slf4j
@Service
public class QualityPositionServiceImpl extends ServiceImpl<QualityPositionMapper, QualityPosition> implements QualityPositionService {

    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Autowired
    private QualityInspectionMapper qualityInspectionMapper;

    @Autowired
    private QualityQuestionInfoMapper qualityQuestionInfoMapper;

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private LaborCompanyProjectMapper laborCompanyProjectMapper;

    @Autowired
    private LinkappUserMapper linkappUserMapper;

    @Autowired
    private QualityDrawingMapper qualityDrawingMapper;

    @Autowired
    private ActualMeasureInfoMapper actualMeasureInfoMapper;

    @Autowired
    private ConcreteStrengthInfoMapper concreteStrengthInfoMapper;

    @Autowired
    private QualityAppraisingExcellentMapper qualityAppraisingExcellentMapper;

    @Autowired
    private HiddenDangerMapper hiddenDangerMapper;

    /**
     * 增加
     *
     * @param qualityPosition
     */
    @Override
    public void insert(QualityPosition qualityPosition) {
        /**
         * 验证重复
         */
        this.checkExist(qualityPosition);
        //设置编码
        this.setCodeAndLevel(qualityPosition);
        //设置基本属性
        this.setBase(qualityPosition);
        this.save(qualityPosition);
        //设置全名称和全路径
        this.setFull(qualityPosition);
    }

    /**
     * 根据id编辑
     *
     * @param qualityPosition
     */
    @Override
    public void updateOne(QualityPosition qualityPosition) {
        /**
         * 验证重复
         */
        this.checkExist(qualityPosition);
        //编辑设置全名称和全路径
        this.setEditFull(qualityPosition);
        //设置基本属性
        this.setBase(qualityPosition);
        this.updateById(qualityPosition);
    }

    /**
     * 编辑设置全名称和全路径
     *
     * @param qualityPosition
     */
    private void setEditFull(QualityPosition qualityPosition) {
        //与旧数据name对比
        QualityPosition old = baseMapper.selectById(qualityPosition.getId());
        if (!qualityPosition.getName().equals(old.getName())) {
            //查询全部子节点
            QueryWrapper<QualityPosition> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("full_id_", "/" + qualityPosition.getId() + "/");
            List<QualityPosition> positionList = baseMapper.selectList(queryWrapper);
            String fullName = old.getFullName();
            int i = fullName.lastIndexOf("/");
            if (i > 0) {
                qualityPosition.setFullName(fullName.substring(0, i + 1) + qualityPosition.getName());
            } else {
                qualityPosition.setFullName(qualityPosition.getName());
            }
            this.setSonFullName(qualityPosition, positionList);
        }
    }

    /**
     * 列表查询
     *
     * @param qualityPositionDTO
     * @return
     */
    @Override
    public List<QualityPositionDTO> queryList(QualityPositionDTO qualityPositionDTO) {
        //查询全部数据
        QueryWrapper<QualityPosition> queryWrapper = new QueryWrapper<>();
        String tenantId = qualityPositionDTO.getTenantId();
        if(StringUtils.isBlank(tenantId)){
            tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        }
        //设置查询条件
        queryWrapper.eq("tenant_id_", tenantId)
                .eq("type_", qualityPositionDTO.getType())
                .orderByAsc("level_", "create_time_");
        List<QualityPosition> positionList = baseMapper.selectList(queryWrapper);
        List<QualityPositionDTO> qualityPositionDTOS = BeanUtil.copyToList(positionList, QualityPositionDTO.class);
        Integer id = qualityPositionDTO.getId();
        if (positionList.size() > 0) {
            //查询图纸数量
            List<Integer> ids = positionList.stream().map(p -> p.getId())
                    .collect(Collectors.toList());
            QueryWrapper<QualityDrawing> drawingQueryWrapper = new QueryWrapper<>();
            drawingQueryWrapper.in("position_id_", ids);
            List<QualityDrawing> drawingList = qualityDrawingMapper.selectList(drawingQueryWrapper);
            id = null == id ? positionList.get(0).getId() : id;
            Integer finalId = id;
            QualityPosition position = positionList.stream().filter(p -> p.getId().equals(finalId))
                    .collect(Collectors.toList()).get(0);
            String[] strings = position.getFullId().split("/");
            Set<Integer> set = new HashSet<>();
            Arrays.stream(strings).forEach(s -> {
                if (StringUtils.isNotBlank(s)) {
                    set.add(Integer.valueOf(s));
                }
            });
            set.remove(id);
            qualityPositionDTOS.forEach(q -> {
                if (set.contains(q.getId())) {
                    q.setExpand(true);
                }
                long count = drawingList.stream().filter(d -> q.getId().equals(d.getPositionId())).count();
                q.setCount((int) count);
            });
        }
        //组织分包单位名称
        this.setSubcontractorName(qualityPositionDTOS,tenantId);
        //整改人，通知人名称
        this.setUserName(qualityPositionDTOS,tenantId);
        //组织数据
        List<QualityPositionDTO> result = qualityPositionDTOS.stream()
                .filter(q -> Integer.valueOf(1).equals(q.getLevel()))
                .collect(Collectors.toList());
        this.setChildren(result, qualityPositionDTOS, id);
        return result;
    }

    /**
     * 整改人，通知人名称
     *
     * @param qualityPositionDTOS
     */
    private void setUserName(List<QualityPositionDTO> qualityPositionDTOS,String tenantId) {
        if(StringUtils.isEmpty(tenantId)){
            tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        }
        LinkappUser linkappUser = new LinkappUser();
        linkappUser.setTenantId(tenantId);
        List<LinkappUser> users = linkappUserMapper.selectUsers(linkappUser);
        qualityPositionDTOS.forEach(q -> {
            if (null != q.getRectifyId()) {
                List<LinkappUser> userList = users.stream().filter(u -> u.getId().equals(q.getRectifyId()))
                        .collect(Collectors.toList());
                if (userList.size() > 0) {
                    q.setRectifyName(userList.get(0).getNickname());
                }
            }
            if (StringUtils.isNotBlank(q.getNoticeId())) {
                String[] strings = q.getNoticeId().split(",");
                List<Long> list = Arrays.stream(strings).map(s -> Long.valueOf(s))
                        .collect(Collectors.toList());
                List<String> name = new ArrayList<>();
                list.forEach(l -> {
                    List<LinkappUser> userList = users.stream().filter(u -> u.getId().equals(l))
                            .collect(Collectors.toList());
                    if (userList.size() > 0) {
                        name.add(userList.get(0).getNickname());
                    }
                });
                q.setNoticeName(StringUtils.join(name, ","));
            }
        });
    }

    /**
     * 设置分包单位名称
     *
     * @param qualityPositionDTOS
     */
    private void setSubcontractorName(List<QualityPositionDTO> qualityPositionDTOS,String tenantId) {
        if(StringUtils.isBlank(tenantId)){
            tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        }
        //查询班组
        GroupDTO groupDTO = new GroupDTO();
        groupDTO.setTenantId(tenantId);
        List<GroupDTO> groupDTOList = groupMapper.queryListByPage(groupDTO);
        //查询参建单位
        LaborCompanyProjectDTO laborCompanyProjectDTO = new LaborCompanyProjectDTO();
        laborCompanyProjectDTO.setTenantId(tenantId);
        List<LaborCompanyProjectDTO> laborCompanyProjectDTOS = laborCompanyProjectMapper
                .queryListByPage(laborCompanyProjectDTO);
        qualityPositionDTOS.forEach(q -> {
            if (Integer.valueOf(1).equals(q.getSubcontractorType())) {
                List<LaborCompanyProjectDTO> dtos = laborCompanyProjectDTOS.stream()
                        .filter(l -> l.getCompanyProjectId().equals(q.getSubcontractor()))
                        .collect(Collectors.toList());
                if (dtos.size() > 0) {
                    q.setSubcontractorName(dtos.get(0).getName());
                }
            } else {
                List<GroupDTO> dtoList = groupDTOList.stream()
                        .filter(g -> g.getId().equals(q.getSubcontractor()))
                        .collect(Collectors.toList());
                if (dtoList.size() > 0) {
                    GroupDTO dto = dtoList.get(0);
                    q.setSubcontractorName(dto.getCompanyName() + "/" + dto.getName());
                }
            }
        });
    }

    /**
     * @Description: 删除部位（包含批量删除）
     * @author kan yuanfeng
     * @date 2020/11/04 11:42
     */
    @Override
    public void delBatch(Set<Integer> ids) {
        ids.forEach(id -> {
            //查询全部子节点
            QueryWrapper<QualityPosition> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("full_id_", "/" + id + "/");
            List<QualityPosition> positionList = baseMapper.selectList(queryWrapper);
            Set<Integer> set = positionList.stream().map(p -> p.getId()).collect(Collectors.toSet());
            if (set.size() > 0) {
                //查询是否关联问题和巡检记录
                QueryWrapper<QualityInspection> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.in("position_id_", set);
                Integer integer1 = qualityInspectionMapper.selectCount(queryWrapper1);
//      check_part_id
                QueryWrapper<QualityQuestionInfo> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.in("check_part_id", set);
                Integer integer2 = qualityQuestionInfoMapper.selectCount(queryWrapper2);
                //查询关联实测实量库
                QueryWrapper<ActualMeasureInfo> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.in("position_id",set);
                queryWrapper3.eq("delete_state",1);
                Integer integer3 = actualMeasureInfoMapper.selectCount(queryWrapper3);

                //查询关联混凝土强度
                QueryWrapper<ConcreteStrengthInfo> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.in("position_id",set);
                queryWrapper4.eq("delete_state",1);
                Integer integer4 = concreteStrengthInfoMapper.selectCount(queryWrapper4);

                //查询关联质量评优
                QueryWrapper<QualityAppraisingExcellent> queryWrapper5 = new QueryWrapper<>();
                queryWrapper5.in("check_part_id",set);
                queryWrapper5.eq("delete_state",1);
                Integer integer5 = qualityAppraisingExcellentMapper.selectCount(queryWrapper5);


                //安全台账
                QueryWrapper<HiddenDanger> queryWrapper6 = new QueryWrapper<>();
                queryWrapper6.in("check_part_id",set);
                Integer integer6 = hiddenDangerMapper.selectCount(queryWrapper6);

                if (integer1 > 0 || integer2 > 0 || integer3>0 || integer4>0 || integer5>0 || integer6>0) {
                    throw new BusinessException("该部位或下属子部位已被使用，无法删除！");
                }
            }
            baseMapper.deleteById(id);
            //删除子节点
            baseMapper.delete(queryWrapper);
        });
    }

    @Override
    public JSONObject excelImport(MultipartFile file, Integer type,LinkappUser linkappUser) {
        JSONObject result = new JSONObject();
        result.put("fail", 0);
//        LinkappUser linkappUser = linkappUserContextProducer.getNotNullCurrent();
        //列头
        Map<String, String> headMp = new HashMap<>();
        headMp.put("部位编号", "code");
        headMp.put("部位名称", "name");
        headMp.put("整改人联系电话", "rectifyId");
        headMp.put("通知人联系电话", "noticeId");
        headMp.put("说明", "remark");
        List<List<String>> excelDataLs = null;
        try {
            //读取信息
            excelDataLs = ExcelReadUtil.getExcelInfo(file, 0, null, -1);
        } catch (Exception e) {
            log.error("---Excel数据导入失败，原因：", e.getMessage());
            throw new BusinessException("Excel数据导入异常");
        }
        if (CollectionUtil.isNotEmpty(excelDataLs)) {
            //读取数据转map list
            List<Map<String, String>> positionMapLs = transToPositionList(excelDataLs, headMp);

            //处理父级
            Map<String, String> parentNameMap = transParentName(positionMapLs);
            List<Map<String, String>> errorMsg = new ArrayList<>();
            List<Map<String, String>> successData = new ArrayList<>();
            //数据校验
            boolean valPass = checkExcelData(positionMapLs, parentNameMap);
            errorMsg = positionMapLs.stream()
                    .filter(item -> StringUtils.isNotBlank(item.get("errorMsg")))
                    .collect(Collectors.toList());

            //执行导入
            transAndInsert(positionMapLs, linkappUser, errorMsg, successData, type);
            result.put("error", errorMsg);
            result.put("success", successData);
            return result;
        } else {
//          return RestBuilders.errorBuilder().message("Excel数据为空").build();
            throw new BusinessException("Excel数据为空");
        }
    }

    @Override
    public RestMessage queryListWithConcreteNum(QualityPositionDTO qualityPositionDTO) {
        LinkappUser linkappUser = linkappUserContextProducer.getNotNullCurrent();
        qualityPositionDTO.setTenantId(linkappUser.getTenantId());
        List<ConcreteStrengthPositionDTO> list = this.baseMapper.queryListWithConcreteNum(qualityPositionDTO);

        return RestBuilders.successBuilder().data(list).build();
    }

    @Override
    public RestMessage queryByParam(QualityPositionVo qualityPositionVo) {
        //模糊查询会查询父级、子集
        LinkappUser linkappUser = linkappUserContextProducer.getNotNullCurrent();
        String tenantId = linkappUser.getTenantId();
        qualityPositionVo.setTenantId(tenantId);
        List<QualityPosition> positionList = baseMapper.queryByParam(qualityPositionVo);

        return RestBuilders.successBuilder().data(positionList).build();
    }


    @Override
    public RestMessage queryListWithMeasureNum(QualityPositionDTO qualityPositionDTO) {
        LinkappUser linkappUser = linkappUserContextProducer.getNotNullCurrent();
        qualityPositionDTO.setTenantId(linkappUser.getTenantId());
        List<ActualMeasurePositionDTO> list = this.baseMapper.queryListWithMeasureNum(qualityPositionDTO);

        return RestBuilders.successBuilder().data(list).build();
    }

    /**
     * @param positionMapLs 部位数据
     * @param linkappUser   当前登录用户
     * @return
     */
    private Map<String, Integer> transAndInsert(List<Map<String, String>> positionMapLs, LinkappUser linkappUser, List<Map<String, String>> error, List<Map<String, String>> success, Integer type) {
        Map<String, Long> userMp = new HashMap<>();

        Map<String, Integer> mp = new HashMap<>();
        Map<String, QualityPosition> dtoMp = new HashMap<>();
        Map<String, String> c = null;
        for (int i = 0; i < positionMapLs.size(); i++) {
            c = positionMapLs.get(i);
            if (StringUtils.isNotBlank(c.get("errorMsg"))) {
                continue;
            }
            String fullName = c.get("fullName");
            String code = c.get("code");
            String name = c.get("name");
            String rectifyId = c.get("rectifyId");
            String noticeId = c.get("noticeId");
            String remark = c.get("remark");
            String parentCode = c.get("parentCode");
            String level = c.get("level");
            //查询用户
            try {
                selectCacheUser(linkappUser.getTenantId(), rectifyId, noticeId, userMp);
                //保存用户
                saveAndCache(linkappUser, userMp, dtoMp, c, type);
                success.add(c);
            } catch (Exception e) {
                Map<String, String> errorData = new HashMap<>();
                errorData.put("rowNo", String.valueOf(i + 2));
                errorData.put("errorMsg", e.getMessage());
                errorData.put("code", c.get("code"));
                errorData.put("name", c.get("name"));
                error.add(errorData);
            }
        }
        return mp;
    }

    /**
     * 保存并缓存
     *
     * @param linkappUser 当前登录用户
     * @param userMp      用户map
     * @param dtoMp       部位map
     * @param c           excel单数据
     */
    private void saveAndCache(LinkappUser linkappUser, Map<String, Long> userMp, Map<String, QualityPosition> dtoMp, Map<String, String> c, Integer type) {
        String fullName = c.get("fullName");
        String code = c.get("code");
        String name = c.get("name");
        String rectifyId = c.get("rectifyId");
        String noticeId = c.get("noticeId");
        String remark = c.get("remark");
        String parentCode = c.get("parentCode");
        String level = c.get("level");

        String[] fullNameArr = fullName.split("/");
        String[] codeArr = code.split("[.]");
        if (ArrayUtil.isNotEmpty(fullNameArr)) {
            Integer len = fullNameArr.length;
            for (int i = 0; i < len; i++) {
                String inName = fullNameArr[i];
                String tmpName = getCurFullName(fullNameArr, i);
                if (StringUtils.isNotBlank(tmpName) && tmpName.contains("null")) {
                    throw new BusinessException("缺少父级");
                }

                String tmpCode = getCurCode(codeArr, i);
                QualityPosition position = dtoMp.get(tmpName);
                if (position == null) {
                    //数据库里找
                    position = getPositionByFullNameAndTenantId(linkappUser.getTenantId(), tmpName, type);
                    if (position == null) {
                        QualityPosition parentPos = null;
                        String posLevel = "1";
                        if (i != 0) {
                            parentPos = dtoMp.get(tmpName.substring(0, tmpName.lastIndexOf("/")));
                            posLevel = String.valueOf(parentPos.getLevel() + 1);
                        }
                        position = initPosition(posLevel, parentPos, tmpCode, inName, remark, userMp, rectifyId, noticeId, linkappUser);
                        position.setType(type);
                        saveAndUpdateFullId(position);
                    } else if (i == len - 1) {
                        throw new BusinessException("数据已存在，重复");
                    }
                    dtoMp.put(tmpName, position);
                }
            }
        }

    }

    /**
     * 获取当前code
     *
     * @param codeArr 编码数组
     * @param ind     层
     * @return 编码
     */
    private String getCurCode(String[] codeArr, int ind) {
        if (ind == 0) {
            return codeArr[0];
        }
        StringJoiner sj = new StringJoiner(".");
        for (int a = 0; a <= ind; a++) {
            sj.add(codeArr[a]);
        }
        return sj.toString();
    }

    /**
     * 获取fullname
     *
     * @param fullNameArr fullname数组
     * @param ind         层
     * @return fullname
     */
    private String getCurFullName(String[] fullNameArr, int ind) {
        if (ind == 0) {
            return fullNameArr[0];
        }
        StringJoiner sj = new StringJoiner("/");
        for (int a = 0; a <= ind; a++) {
            sj.add(fullNameArr[a]);
        }
        return sj.toString();
    }

    /**
     * 保存并更新fullid
     *
     * @param position
     */
    private void saveAndUpdateFullId(QualityPosition position) {
        this.baseMapper.insert(position);
        String fullId = "";
        String pFullId = position.getFullId();
        if (StringUtils.isNotBlank(pFullId)) {
            fullId = position.getFullId() + position.getId() + "/";
        } else {
            fullId = "/" + position.getId() + "/";
        }
        position.setFullId(fullId);
        this.baseMapper.updateById(position);
    }


    /**
     * 初始化部位
     *
     * @param level       层
     * @param parrent     父级
     * @param code        编码
     * @param name        名称
     * @param remark      说明
     * @param userMp      用户map
     * @param rectifyId   整改人
     * @param noticeId    通知人
     * @param linkappUser 当前登录用户
     * @return 部位
     */
    private QualityPosition initPosition(String level, QualityPosition parrent, String code, String name, String remark, Map<String, Long> userMp, String rectifyId, String noticeId, LinkappUser linkappUser) {
        QualityPosition pos = new QualityPosition();
        pos.setLevel(Integer.parseInt(level));
        pos.setCode(code);

        pos.setName(name);
        pos.setRemark(remark);
        pos.setTenantId(linkappUser.getTenantId());
        if (parrent == null) {
            pos.setParentId(0);
            pos.setFullName(name);
            pos.setFullId("");
        } else {
            pos.setParentId(parrent.getId());
            pos.setFullName(parrent.getFullName() + "/" + name);
            pos.setFullId(parrent.getFullId());
        }

        if (StringUtils.isNotBlank(rectifyId)) {
            pos.setRectifyId(userMp.get(rectifyId));
        }
        if (StringUtils.isNotBlank(noticeId)) {
            if (noticeId.indexOf("，") > -1) {
                noticeId = noticeId.replaceAll("，", ",");
            }
            StringJoiner sj = new StringJoiner(",");
            String[] noticeIds = noticeId.split(",");
            for (int i = 0; i < noticeIds.length; i++) {
                String tmpId = noticeIds[i];
                Long uid = userMp.get(tmpId);
                if (uid != null) {
                    sj.add(String.valueOf(uid));
                }
            }
            pos.setNoticeId(sj.toString());
        }

        pos.setOrder(1);


        pos.setCreateTime(DateUtil.date());
        pos.setCreatorId(linkappUser.getId());
        pos.setModifyId(pos.getCreatorId());
        pos.setModifyTime(pos.getCreateTime());

        return pos;
    }

    /**
     * 查询并缓存用户
     *
     * @param tenantId  租户id
     * @param rectifyId 整改人id
     * @param noticeId  通知人id
     * @param userMp    用户map
     */
    private void selectCacheUser(String tenantId, String rectifyId, String noticeId, Map<String, Long> userMp) {
        if (StringUtils.isNotBlank(rectifyId)) {
            LinkappUser rectUserExp = new LinkappUser();
            rectUserExp.setTenantId(tenantId);
            rectUserExp.setPhone(rectifyId);
            LinkappUser rectUser = linkappUserMapper.selectOneUserByTenantPhone(rectUserExp);
            if (rectUser != null) {
                userMp.put(rectifyId, rectUser.getId());
            }
        }
        if (StringUtils.isNotBlank(noticeId)) {
            if (noticeId.indexOf("，") > -1) {
                noticeId = noticeId.replaceAll("，", ",");
            }
            String[] noticeIds = noticeId.split(",");

            QueryWrapper qw = new QueryWrapper();
            qw.eq("tenant_id", tenantId);
            qw.eq("delete_state", 1);
            qw.in("phone", noticeIds);
            List<LinkappUser> userList = linkappUserMapper.selectList(qw);
            if (CollectionUtil.isNotEmpty(userList)) {
                userList.stream().forEach(c -> {
                    userMp.put(c.getPhone(), c.getId());
                });
            }
        }
    }

    /**
     * 通过租户id、全名查询部位
     *
     * @param tenantId 租户id
     * @param fullName 全名
     * @return 部位
     */
    private QualityPosition getPositionByFullNameAndTenantId(String tenantId, String fullName, Integer type) {
        //校验名称
        QueryWrapper<QualityPosition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id_", tenantId);
        queryWrapper.eq("full_name_", fullName);
        queryWrapper.eq("type_", type);
        QualityPosition position = this.baseMapper.selectOne(queryWrapper);
        return position;
    }


    /**
     * 转换父级名称
     *
     * @param positionMapLs 部位maplist
     * @return 父级名称map
     */
    private Map<String, String> transParentName(List<Map<String, String>> positionMapLs) {
        Map<String, String> parentMp = new HashMap<>();
        if (CollectionUtil.isNotEmpty(positionMapLs)) {
            positionMapLs.stream().forEach(c -> {
                String code = c.get("code");
                String name = c.get("name");
                parentMp.put(code, name);
            });
        }
        return parentMp;
    }

    /**
     * 校验Excel数据
     *
     * @param positionMapLs 部位数据Map list
     * @param parentNameMap 父级名称map
     * @return 校验结果
     */
    private boolean checkExcelData(List<Map<String, String>> positionMapLs, Map<String, String> parentNameMap) {
        boolean valiPass = true;
        Map<String, Integer> czMp = new HashMap<>();
        if (CollectionUtil.isNotEmpty(positionMapLs)) {
            for (int i = 0; i < positionMapLs.size(); i++) {
                Map<String, String> mp = positionMapLs.get(i);
                String code = mp.get("code");
                String name = mp.get("name");

                if (StringUtils.isBlank(name)) {
                    mp.put("errorMsg", "部位名称为空");
                    mp.put("rowNo", String.valueOf(i + 2));
                    valiPass = false;
                    continue;
                }

                //全名
                String fullName = transFullName(code, name, parentNameMap);

                //校验名称
                if (czMp.containsKey(fullName)) {
                    Integer czIndex = czMp.get(fullName);
                    mp.put("errorMsg", "部位名称" + (i + 2) + "行与" + (czIndex + 2) + "行重复");
                    mp.put("rowNo", String.valueOf(i + 2));
                    valiPass = false;
                    continue;
                }
                czMp.put(fullName, i);
                mp.put("fullName", fullName);
            }
        }
        return valiPass;
    }

    /**
     * 处理转换fullname
     *
     * @param parentCode    父级code
     * @param name          名称
     * @param parentNameMap 父级map
     * @return fullname
     */
    private String transFullName(String parentCode, String name, Map<String, String> parentNameMap) {
        if (parentCode.indexOf(".") < 0) {
            return parentNameMap.get(parentCode);
        } else {
            String pcode = parentCode.substring(0, parentCode.lastIndexOf("."));
            String pname = transFullName(pcode, parentNameMap.get(pcode), parentNameMap);
            return pname + "/" + name;
        }
    }

    /**
     * @param excelDataLs excel数据list
     * @param headMp      列头map
     * @return 数据kist
     */
    private List<Map<String, String>> transToPositionList(List<List<String>> excelDataLs, Map<String, String> headMp) {
        log.info(JSONUtil.toJsonStr(excelDataLs));
        Map<Integer, String> dataIndexMp = new HashMap<>();
        List<Map<String, String>> dataMpLs = new ArrayList<>();


        for (int i = 0; i < excelDataLs.size(); i++) {
            List<String> strLs = excelDataLs.get(i);
            if (i == 0) {
                for (int n = 0; n < strLs.size(); n++) {
                    String tmpName = strLs.get(n);
                    String code = headMp.get(tmpName);
                    if (StringUtils.isBlank(code)) {
                        Assert.isFalse(StringUtils.isBlank(code), "模板列头设置不正确");
                        break;
                    }
                    dataIndexMp.put(n + 1, code);
                }
            } else {
                Map<String, String> tmp = new HashMap<>();
                for (int n = 0; n < strLs.size(); n++) {
                    String code = dataIndexMp.get(n + 1);
                    String val = strLs.get(n);
                    tmp.put(code, val);
                    if ("code".equals(code) && StringUtils.isNotBlank(val)) {
                        if (val.indexOf(".") > 0) {
                            tmp.put("parentCode", val.substring(0, val.lastIndexOf(".")));
                        } else {
                            tmp.put("parentCode", val);
                        }
                        tmp.put("level", String.valueOf(StrUtil.count(val, ".") + 1));
                    }
                }
                dataMpLs.add(tmp);
            }
        }
        return dataMpLs;
    }

    /**
     * 设置子节点数据
     *
     * @param result
     * @param qualityPositionDTOS
     */
    private void setChildren(List<QualityPositionDTO> result, List<QualityPositionDTO> qualityPositionDTOS, Integer id) {
        result.forEach(r -> {
            if (r.getId().equals(id)) {
                r.setSelected(true);
            }
            List<QualityPositionDTO> sonList = qualityPositionDTOS.stream()
                    .filter(q -> r.getId().equals(q.getParentId()))
                    .collect(Collectors.toList());
            r.setChildren(sonList);
            if (sonList.size() > 0) {
                this.setChildren(sonList, qualityPositionDTOS, id);
            }
        });
    }

    /**
     * 验证重复
     */
    private void checkExist(QualityPosition qualityPosition) {
        QueryWrapper<QualityPosition> queryWrapper = new QueryWrapper<>();
        //设置判断重复条件
        queryWrapper.eq("parent_id_", qualityPosition.getParentId())
                .eq("name_", qualityPosition.getName())
                .eq("type_", qualityPosition.getType())
                .eq("tenant_id_", linkappUserContextProducer.getNotNullCurrent().getTenantId());
        //编辑的时候存在id
        Optional.ofNullable(qualityPosition.getId()).ifPresent(id -> queryWrapper.ne("id", qualityPosition.getId()));
        Integer integer = baseMapper.selectCount(queryWrapper);
        if (integer > 0) {
            throw new BusinessException("该部位已存在");
        }
    }

    /**
     * 设置基本属性
     *
     * @param qualityPosition
     */
    private void setBase(QualityPosition qualityPosition) {
        qualityPosition.setModifyTime(new Date());
        qualityPosition.setModifyId(linkappUserContextProducer.getCurrent().getId());
        //没有id就是新增,有就是编辑
        if (null == qualityPosition.getId()) {
            qualityPosition.setCreatorId(linkappUserContextProducer.getCurrent().getId());
            qualityPosition.setCreateTime(new Date());
            qualityPosition.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        }
    }

    /**
     * 设置全名称和全路径
     *
     * @param qualityPosition
     */
    private void setFull(QualityPosition qualityPosition) {
        //查找问题类别
        qualityPosition.setFullName(qualityPosition.getName());
        QualityPosition position = baseMapper.selectById(qualityPosition.getParentId());
        if (null == position) {
            qualityPosition.setFullId("/" + qualityPosition.getId() + "/");
        } else {
            qualityPosition.setFullId(position.getFullId() + (qualityPosition.getId() + "") + "/");
            qualityPosition.setFullName(position.getFullName() + "/" + qualityPosition.getName());
        }
        baseMapper.updateById(qualityPosition);
    }

    /**
     * 设置编码
     *
     * @param qualityPosition
     */
    private void setCodeAndLevel(QualityPosition qualityPosition) {
        String code = "1";
        Integer level = 1;
        Integer order = 1;
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        QueryWrapper<QualityPosition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id_", tenantId)
                .eq("parent_id_", qualityPosition.getParentId())
                .orderByDesc("order_");
        List<QualityPosition> positions = baseMapper.selectList(queryWrapper);
        if (null != positions && positions.size() > 0) {
            QualityPosition sonPosition = positions.get(0);
            level = sonPosition.getLevel();
            String positionCode = sonPosition.getCode();
            code = positionCode.substring(0, positionCode.lastIndexOf(".") + 1) + (sonPosition.getOrder() + 1);
            order = sonPosition.getOrder() + 1;
        } else {
            //查询父级
            QualityPosition position = baseMapper.selectById(qualityPosition.getParentId());
            if (null != position) {
                code = position.getCode() + ".1";
                level = position.getLevel() + 1;
            }
        }
        qualityPosition.setCode(code);
        qualityPosition.setLevel(level);
        qualityPosition.setOrder(order);
    }

    /**
     * 设置子节点全名称
     *
     * @param parent
     * @param positionList
     */
    private void setSonFullName(QualityPosition parent, List<QualityPosition> positionList) {
        //查询子节点
        List<QualityPosition> sonList = positionList.stream()
                .filter(p -> parent.getId().equals(p.getParentId()))
                .collect(Collectors.toList());
        if (sonList.size() > 0) {
            sonList.forEach(s -> {
                s.setFullName(parent.getFullName() + "/" + s.getName());
                this.updateById(s);
                this.setSonFullName(s, positionList);
            });
        }
    }

}
